﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Ninject;
using Jo.PropertyManagement.DataAccess.AbstractRepository;
using Jo.PropertyManagement.Domain.Entity;
using Jo.PropertyManagement.DataAccess.Helper;

namespace Jo.PropertyManagement.DataAccess.Repository
{
    public class CustomerRepository : ICustomerRepository
    {
        //[Inject]
        //public ISessionFactory CustomSessionFactory { get; set; }
        ISessionFactory sessionFactory;
        public CustomerRepository()
        {
            sessionFactory = FluentHibernateHelper.SessionFactory;
        }

        public Customer CreateCustomer(Customer customer)
        {
            var session = sessionFactory.OpenSession();
            using (var transaction = session.BeginTransaction())
            {
                customer = (Customer)session.SaveOrUpdateCopy(customer);
                transaction.Commit();
            }
            return customer;
        }

        public Customer GetLogInCustomer(Customer customer)
        {
            Customer result = null;
            var session = sessionFactory.OpenSession();
            using (var transaction = session.BeginTransaction())
            {
                IQuery query = session.CreateQuery("from Customer c where c.Email='" + customer.Email + "' and c.Password='" + customer.Password + "'");
                IList<Customer> lstCustomer = query.List<Customer>();
                if (lstCustomer.Count > 0)
                {
                    result = lstCustomer[0];
                }
                transaction.Commit();
            }
            return result;
        }

        public Customer GetLogInCustomerById(long customerId)
        {
            Customer result = null;
            var session = sessionFactory.OpenSession();
            using (var transaction = session.BeginTransaction())
            {
                IQuery query = session.CreateQuery("from Customer c where c.Id=" + customerId);
                IList<Customer> lstCustomer = query.List<Customer>();
                if (lstCustomer.Count > 0)
                {
                    result = lstCustomer[0];
                }
                transaction.Commit();
            }
            return result;
        }

        public int UpdateCustomer(Customer customer)
        {
            var session = sessionFactory.OpenSession();
            using (var transaction = session.BeginTransaction())
            {
                session.SaveOrUpdate(customer);
                transaction.Commit();
            }
            return 1;
        }
    }
}
